<template>
  <div>
    <div class="app_card mb-2 pt-4 pb-4">
      <div class="d-flex justify-content-between search-form">
        <div class="flex-grow-1">
          <el-select class="w100px mr-3" v-model="queryParam.pullStatus" placeholder="拉取状态">
            <el-option label="拉取状态" :value="null" />
            <el-option v-for="item in pullingStateOption" :key="item.value" :label="item.label"
              :value="Number(item.value)" />
          </el-select>
          <div class="el-select w250px mr-3">
            <el-date-picker style="width:220px" v-model="queryParam.time" type="daterange" value-format="YYYY-MM-DD"
              range-separator="到" start-placeholder="开始时间" end-placeholder="结束时间" />
          </div>
          <el-input class="w350px mr-3" v-model.trim="queryParam.searchValue" autocomplete="off"
            placeholder="标题/课程/学院/教师/教室">
            <template #prepend>
              <el-select class="w100px" v-model="queryParam.searchTitle" placeholder="请选择">
                <el-option label="标题" value="title" />
                <el-option label="课程" value="courseName" />
                <el-option label="学院" value="academyName" />
                <el-option label="教师" value="teacherName" />
                <el-option label="教室" value="classroomName" />
              </el-select>
            </template>
          </el-input>
          <el-button type="primary"  @click="onRefresh()" style="margin-left: 1rem;" >搜索</el-button>
          <el-button type="primary" plain @click="onReset()">重置</el-button>
        </div>
        <div class="d-flex">
           <el-radio-group class="radio_button" v-model="queryParam.inUse">
              <el-radio :label="null">全部</el-radio>
              <el-radio :label="1">已上架课程</el-radio>
              <el-radio :label="2">已下架课程</el-radio>
            </el-radio-group>
            <el-button type="primary" plain @click="onOffRow(null)">批量下架</el-button>
            <el-button type="primary" plain @click="onRow(null)">批量上架</el-button>
          </div>
      </div>
    </div>
    <div class="app_card pt-4  pb-5">
      <el-table stripe size="large" :data="dataOfTable" height="calc(100vh - 300px)"
        @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="50" />
        <el-table-column label="课程名称" prop="courseName" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.Course.name }}</template>
        </el-table-column>
        <el-table-column label="教师名称" prop="teacherName" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.Teacher?.name }}</template>
        </el-table-column>
        <el-table-column label="拉取状态" prop="pullingState" align="center" show-overflow-tooltip>
          <template #default="scope">
            <div v-html="PULLING_STATE_NODE_MAP[scope.row.pullStatus]"></div>
          </template>
        </el-table-column>
        <el-table-column label="录制时间" prop="actionTime" align="center" width="170">
          <template #default="scope">{{ scope.row.classDay }} {{ scope.row.startTime }}</template>
        </el-table-column>
        <el-table-column label="浏览量" prop="pageviews" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.watchNum }}</template>
        </el-table-column>
        <el-table-column label="封面" prop="image" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-image :preview-teleported="true" style="height: 30px" :src="scope.row.image" :zoom-rate="1.2"
              :max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.image]" :initial-index="0" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="title" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.title }}</template>
        </el-table-column>
        <el-table-column label="所属教室" prop="roomName" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.Room?.Name }}</template>
        </el-table-column>
        <el-table-column label="状态" prop="releaseState" align="center" show-overflow-tooltip>
          <template #default="scope">
            <div v-html="INUSENODEMAP(scope.row)"></div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="发布状态" prop="releaseState" align="center" show-overflow-tooltip>
          <template #default="scope">
            <div v-html="IS_PUBLISH_NODE_MAP[[scope.row.isPublish, scope.row.isLegal].join('')]"></div>
          </template>
        </el-table-column> -->

        <el-table-column label="操作" width="320">
          <template #default="scope">
            <!-- '0': '待发布','1': '待审核','2': '审核失败：涉黄涉赌', -->
            <!--            <el-button link type="primary" @click="onCloseRow(scope.row)">取消申请</el-button>-->
            <el-button link type="primary" v-if="scope.row.isLegal === 2"
              @click="onSubmitAudit(scope.row)">请求重新审核</el-button>
            <el-button link type="primary" v-if="scope.row.pullStatus === 0" @click="onPulling(scope.row)">手动拉取</el-button>
            <el-button link type="primary" v-if="scope.row.isLegal === 1" @click="onApply(scope.row)">上架分类</el-button>
            <el-button link type="primary" @click="onTitleImgRow(scope.row)">更换标题封面</el-button>
            <el-button link type="primary" @click="vodVideoPreviewRef.show(scope.row.relaFileTaskId)">查看</el-button>
            <!--            <el-button link type="primary" @click="onCourseTeacherRow(scope.row)">修改课程</el-button>-->
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="note" align="center" show-overflow-tooltip />

      </el-table>
      <div class="mt-2">
        <el-pagination background v-model:currentPage="queryParam.page" v-model:page-size="queryParam.pageSize"
          :page-sizes="paginationOption.pageSizes" :layout="paginationOption.layout" :total="paginationOption.count"
          @size-change="handleChangeSize" @current-change="handleChangeCurrent" />
      </div>
    </div>
    <TitleImgDialog ref="titleImgDialogRef" @success="loadData()"></TitleImgDialog>
    <CourseTeacherDialog ref="courseTeacherDialogRef" @success="loadData()"></CourseTeacherDialog>
    <PullingDialog ref="pullingDialogRef" @success="loadData()"></PullingDialog>
    <DetailDialog ref="detailDialogRef" @success="loadData()"></DetailDialog>
    <ApplyDialog ref="applyDialogRef" @success="loadData()"></ApplyDialog>
    <VodVideoPreview ref="vodVideoPreviewRef" @success="loadData()"></VodVideoPreview>
  </div>
</template>

<script setup>
/**
 * 录播资源管理
 */
import { ref, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import useAuthStore from '@/stores/useAuthStore';
import {
  pullingStateList,
  PULLING_STATE_NODE_MAP,
  releaseStateList, IS_PUBLISH_NODE_MAP, IN_USE_NODE_MAP,IS_LEGAL_NODE_MAP
} from '@/apis/model/RecordModel';
import { findValue } from '@/utils/EsCommon';
//组件
import DetailDialog from './DetailDialog.vue';
import ApplyDialog from './ApplyDialog.vue';
import TitleImgDialog from './TitleImgDialog.vue';
import PullingDialog from './PullingDialog.vue';
import CourseTeacherDialog from './CourseTeacherDialog.vue';
import { recordTaskParams } from "@/apis/model/RecordTaskModel";
import VodVideoPreview from "@/components/video-preview/VodVideoPreview.vue";

// ======================================================
//                      变量声明
// ======================================================

const pullingStateOption = ref(pullingStateList);
const releaseStateOption = ref(releaseStateList);

const authStore = useAuthStore();

// 组件引用
const titleImgDialogRef = ref(null);
const detailDialogRef = ref(null);
const pullingDialogRef = ref(null);
const applyDialogRef = ref(null);
const courseTeacherDialogRef = ref(null);
const vodVideoPreviewRef = ref(null);

// 表格数据
const dataOfTable = ref([]);
// 表格查询参数
const queryParam = ref(recordTaskParams())
// 分页栏配置数据
const paginationOption = ref({
  layout: 'total, sizes, prev, pager, next, jumper',
  pageSizes: [10, 20, 50, 100, 500, 1000],
  count: 0,
})
// 表格多选数据
const multipleSelection = ref([]);


// ======================================================
//                      处理事件
// ======================================================
// 点击刷新按钮
const onRefresh = () => {
  queryParam.value.page = 1;
  loadData();
}

//点击重置按钮
const onReset = () => {
  queryParam.value = recordTaskParams()
  loadData()
}

// 处理表格全选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
// 修改课程老师
const onCourseTeacherRow = (row = null) => {
  courseTeacherDialogRef.value.show(row.id, "修改课程老师", row);
}
// 跟换标题封面
const onTitleImgRow = (row = null) => {
  titleImgDialogRef.value.show(row.id, "更换标题封面", row);
}
// 申请发布
const onApply = (row = null) => {
  applyDialogRef.value.show(row.id, "上架分类", row);
}
// 手动拉取
const onPulling = (row = null) => {
  pullingDialogRef.value.show(row.id, "手动拉取", row);
}

// 点击行内编辑按钮
const onEditRow = (row) => {
  detailDialogRef.value.show(row.id, "详情 ", row);
}
const onSubmitAudit = (row) => {
  ElMessageBox.confirm("确认提交审核操作？", "警告", {
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        EsAjax.post(ApiUrls.recordTaskChangeIsLegal, { id: row.id.toString(), isLegal: 0, unlegalId: 0 })
          .then(res => {

            if (res.data.code !== 200) {
              ElMessage.warning(res.data.msg);
              return;
            }
            ElMessage.success("操作成功");
            loadData();
          })
          .catch(err => {
            ElMessage.error("网络错误：", err.message)
          }).finally(() => { instance.confirmButtonLoading = false; done(); });
      } else {
        done()
      }
    }
  })
}
// 取消审核
const onCloseRow = (row) => {
  // let n = multipleSelection.value.length, id = multipleSelection.value.map(v => v.id).toString();
  // if (n) {
  ElMessageBox.confirm("确认取消申请操作？", "警告", {
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        EsAjax.post(ApiUrls.recordTaskChangeIsPublish, { id: row.id, isPublish: 0 })
          .then(res => {

            if (res.data.code !== 200) {
              ElMessage.warning(res.data.msg);
              return;
            }
            ElMessage.success("操作成功");
            loadData();
          })
          .catch(err => {
            ElMessage.error("网络错误：", err.message)
          }).finally(() => { instance.confirmButtonLoading = false; done(); });
      } else {
        done()
      }
    }
  })
  // } else {
  //   ElMessage.info("请选择批量数据");
  // }

}
// 批量下架
const onOffRow = (row) => {
  let n = multipleSelection.value.length, id = multipleSelection.value.map(v => v.id).toString();
  if (n) {
    ElMessageBox.confirm("确认批量下架操作？", "警告", {
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          EsAjax.post(ApiUrls.recordTaskChangeIsUse, { id: id, inUse: 2 })
            .then(res => {
              if (res.data.code !== 200) {
                ElMessage.warning(res.data.msg);
                return;
              }
              ElMessage.success("操作成功");
              loadData();
            })
            .catch(err => {
              ElMessage.error("网络错误：", err.message)
            }).finally(() => {
              instance.confirmButtonLoading = false;
              done();
            });
        } else {
          done()
        }
      }
    })
  } else {
    ElMessage.info("请选择批量数据");
  }
}

// 批量上架
const onRow = () => {
  let n = multipleSelection.value.length, id = multipleSelection.value.map(v => v.id).toString();
  const flag = multipleSelection.value.every(item=>item.isLegal===1)
  if(!flag){
    ElMessage.warning("待审核和审核失败的课程不能上架！")
    return;
  }
  if (n) {
    ElMessageBox.confirm("确认批量上架操作？", "警告", {
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          EsAjax.post(ApiUrls.recordTaskChangeIsUse, { id: id, inUse: 1 })
            .then(res => {
              if (res.data.code !== 200) {
                ElMessage.warning(res.data.msg);
                return;
              }
              ElMessage.success("操作成功");
              loadData();
            })
            .catch(err => {
              ElMessage.error("网络错误：", err.message)
            }).finally(() => {
              instance.confirmButtonLoading = false;
              done();
            });
        } else {
          done()
        }
      }
    })
  } else {
    ElMessage.info("请选择批量数据");
  }
}


// 处理分页尺寸
const handleChangeSize = (val) => {
  console.log(`${val} items per page`);
  queryParam.value.page = 1;
  queryParam.value.pageSize = val;
  loadData();
}

// 处理页码
const handleChangeCurrent = (val) => {
  console.log(`current page: ${val}`)
  queryParam.value.page = val;
  loadData();
}

// ======================================================
//                      处理事件
// ======================================================

const loadData = () => {
  const form = JSON.parse(JSON.stringify(queryParam.value))
  form.startTime = form.time[0]
  form.endTime = form.time[1]
  form[form.searchTitle] = form.searchValue
  delete form.time
  delete form.searchTitle
  delete form.searchValue
  EsAjax.post(ApiUrls.recordTaskResourceList, form).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list, count } = res.data.data
    dataOfTable.value = list;
    console.log(dataOfTable.value)
    paginationOption.value.count = count;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}

//状态判断
const INUSENODEMAP = (row) => {
  if(row.isLegal == 0){
    //待审核
    return IS_LEGAL_NODE_MAP[row.isLegal]
  }else if(row.isLegal == 1){
    //审核通过
    return IN_USE_NODE_MAP[row.isPublish]
  } 
  else {
    //审核失败
    return `<span class="status-red">审核失败：${row.Unlegal?.unlegalName}</span>`
  }
}


onMounted(() => {
  loadData();
})

</script>
<style lang="less" scoped>
// .flex-grow-1 {
//   display: flex;

//   .d-flex {
//     margin-left: 4rem;

//     .radio_button {
//       :deep(.el-radio) {
//         margin-right: 15px;
//       }
//     }
//   }
// }

.d-flex {
  flex-wrap: wrap;
    .radio_button {
      :deep(.el-radio) {
        margin-right: 30px;
      }
    }
  }

.class_name {
  position: absolute;
  font-size: 20px;
  left: 30px;
  top: 10px;
  font-weight: bold;
}</style>

